import { Component, OnInit } from '@angular/core';
import * as echarts from 'echarts';
import { g } from '../service/global-data'

@Component({
    selector: 'app-track-chart',
    templateUrl: './track-chart.html',
})
export class TrackChart implements OnInit {
    dom: any;
    chart: any;
    option: any;
    resizeObserver!: ResizeObserver;

    selected_point = -1;  // 用于在map_canvas中绘制当前轨迹点

    ngOnInit(): void {
        this.dom = document.getElementById('track-chart')!
        this.dom.addEventListener('contextmenu', (event: any) => {
            event.preventDefault();
        });
        
        this.chart = echarts.init(this.dom);

        this.option = {
            title: {
                text: '轨迹海拔统计图（米）',
                show: true,
            },
            tooltip: {
                show: false,
                trigger: 'axis',
                formatter: '{b0}: {c0}米',
                padding: [3, 5],
            },
            grid: {
                top: 20,
                left: 5,
                right: 0,
                bottom: 80,
                containLabel: true,
            },
            xAxis: {
                type: 'category',
            },
            yAxis: {
                type: 'value',
                // min: 'dataMin',
                // max: 'dataMax',
            },
            series: [
                {
                    type: 'bar',
                    // sampling: 'lttb',  // 启用采样后，在地图中选择轨迹点时在chart中可能找不到对应点从而无法显示，故暂屏蔽
                    data: [],
                    selectedMode: 'single',
                    select: {
                        label: {
                            show: false, // 数据量过多时，标签显示有严重延时，原因未知，可暂屏蔽
                            // formatter: '{b0}: {c0}米',
                            position: 'top',
                            distance: 2,
                            color: 'rgb(255,0,0)',
                        },
                        itemStyle: {
                            color: 'rgb(255,0,0)',
                            borderWidth: 0,
                        },
                    },
                    itemStyle: {},
                },
            ]
        };

        this.chart.setOption(this.option);
        this.chart.on('mouseover', { seriesIndex: 0 }, (event: any) => this.onMouseover(event));
        this.chart.on('selectchanged', { seriesIndex: 0 }, (event: any) => this.onSelectChange(event));

        this.resizeObserver = new ResizeObserver((entries) => {
            if (entries.length > 0) {
                this.chart.resize();
            }
        });
        this.resizeObserver.observe(this.dom);

        g.track_chart = this;

        this.dom.addEventListener('mouseenter', () => {
            this.dom.focus();
        });
        this.dom.addEventListener('mouseleave', () => {
            this.dom.blur();
        });
        this.dom.addEventListener('keydown', (event: any) => {
            let step = 0;
            if (event.key === 'ArrowRight') {
                step = 1;
            } else if (event.key === 'ArrowLeft') {
                step = -1;
            }

            let new_index;
            if (this.selected_point >= 0) {
                if (g.editing) {
                    const track_line = g.track_edit.selected_track_line;
                    if (!!track_line) {
                        new_index = this.selected_point + step;
                        if (new_index > track_line.point_num - 1) {
                            new_index = track_line.point_num - 1;
                        }
                        if (new_index < 0) {
                            new_index = 0;
                        }
                    }
                } else {
                    const track_line = g.user_data.selected;
                    if (!!track_line && track_line.type === 'track_line') {
                        new_index = this.selected_point + step;
                        if (new_index > track_line.point_num - 1) {
                            new_index = track_line.point_num - 1;
                        }
                        if (new_index < 0) {
                            new_index = 0;
                        }
                    } 
                }
            }

            if (new_index !== this.selected_point) {
                this.select_point(new_index!);
            }

        });

    }

    refresh() {
        if (g.editing) {
            const track_line = g.track_edit.selected_track_line;
            if (!!track_line) {
                this.option.title.show = false;
                this.option.series[0].select.itemStyle.color = 'rgb(255,0,0)';
                this.option.series[0].select.label.color = 'rgb(255,0,0)';
                this.option.series[0].data = track_line.points.map((point: number[]) => point[2].toFixed(0));
                this.option.series[0].itemStyle = {
                    color: (params: any) => {
                        if (params.dataIndex < track_line.sel_start_idx || params.dataIndex > track_line.sel_end_idx) {
                            return track_line.checked ? 'yellow' : 'blue';
                        } else {
                            return 'green';
                        }
                    },
                };
            } else {
                this.option.title.show = true;
                this.option.series[0].data = [];
                this.option.series[0].itemStyle = {};
            }
        } else {
            const track_line = g.user_data.selected;
            if (!!track_line && track_line.type === 'track_line' && track_line.visible) {
                this.option.title.show = false;
                this.option.series[0].select.itemStyle.color = `rgb(${255 - track_line.red}, ${255 - track_line.green}, ${255 - track_line.blue})`;
                this.option.series[0].select.label.color = `rgb(${255 - track_line.red}, ${255 - track_line.green}, ${255 - track_line.blue})`;
                this.option.series[0].data = g.track_line_points_cache.get(track_line.uuid).map((point: number[]) => point[2].toFixed(0));
                this.option.series[0].itemStyle = {
                    color: () => `rgb(${track_line.red}, ${track_line.green}, ${track_line.blue})`,
                };
            } else {
                this.option.title.show = true;
                this.option.series[0].data = [];
                this.option.series[0].itemStyle = {};
            }
        }

        this.chart.setOption(this.option);
        
        if (g.editing) {
            if (!!g.track_edit.selected_track_line) {
                this.chart.dispatchAction({
                    type: 'select',
                    seriesIndex: 0,
                    dataIndex: g.track_edit.selected_track_line.selected_point,
                });
            }
        } else {
            this.chart.dispatchAction({
                type: 'select',
                seriesIndex: 0,
                dataIndex: -1,
            });
        }
    }

    onMouseover(event: any) {
        this.select_point(event.dataIndex);
    }

    select_point(index: number) {
        this.chart.dispatchAction({
            type: 'select',
            seriesIndex: 0,
            dataIndex: index,
        });
    }

    onSelectChange(event: any) {
        if (event.selected.length > 0) {
            this.selected_point = event.selected[0].dataIndex[0];
        } else {
            this.selected_point = -1;
            return; // 通过refresh将selected_point置为-1时，不应再刷新map_canvas
        }

        if (g.editing) {
            if (!!g.track_edit.selected_track_line) {
                if (event.selected.length > 0) {
                    g.track_edit.selected_track_line.selected_point = event.selected[0].dataIndex[0];
                    g.map_canvas.repaint();
                    g.track_info.refresh();
                }
            }
        } else {
            g.map_canvas.repaint_over_backup();
            g.track_info.refresh();
        }
    }

}

